package com.bawei.composeui2207a.day04.mvi.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch

/**
 * 作者：赵亮
 * 时间：2024/12/13 16:20
 * 功能：
 */
abstract class BaseViewModel : ViewModel() {

    // 存储意图的容器
    private val _channel = Channel<IUiIntent>(Channel.UNLIMITED)

    // 存储状态的容器
    val uiState = MutableStateFlow<UiState>(OnLoading)

    init {
        viewModelScope.launch {
            _channel.receiveAsFlow().collect {
                handIntent(it)
            }
        }
    }

    /**
     * 处理意图的方法
     */
    abstract fun handIntent(it: IUiIntent)

    /**
     * 发送意图
     */
    fun sendIntent(iUiIntent: IUiIntent) {
        viewModelScope.launch {
            _channel.send(iUiIntent)
        }
    }

    /**
     * 网络请求
     */
    fun httpRequest(flow: Flow<*>) {
        viewModelScope.launch {
            flow.flowOn(Dispatchers.IO)
                // 发生异常调用错误
                .catch { uiState.value = OnError(it.message.toString()) }
                // 接收到数据调用成功
                .collect { uiState.value = OnSuccess(it) }
        }
    }
}